package main

import (
	"dbmx/database"
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/tidwall/sjson"
)

// 生成静态文件
// go-bindata -pkg main -o bindata.go static/...

func main() {

	r := gin.Default()

	r.GET("/static/*filepath", func(c *gin.Context) {
		filepath := c.Param("filepath")
		fmt.Println("## filepath:", filepath)
		indexHtml, _ := Asset(fmt.Sprintf("static%s", filepath))
		contentType := "text/plain; charset=utf-8"
		if strings.Contains(filepath, ".html") {
			contentType = "text/html; charset=utf-8"
		} else if strings.Contains(filepath, ".js") {
			contentType = "application/javascript; charset=utf-8"
		} else if strings.Contains(filepath, ".css") {
			contentType = "text/css; charset=utf-8"
		}

		c.Writer.Header().Add("Content-Type", contentType)
		c.Writer.WriteHeader(http.StatusOK)
		c.Writer.Write(indexHtml)
		c.Writer.Flush()
	})

	// curl -X GET http://127.0.0.1:8080/api/getTables
	r.GET("/api/getTables", func(c *gin.Context) {
		rows := database.MysqlClient.ExecuteQuery(`show tables`)
		c.Writer.Header().Add("Content-Type", `application/json; charset=utf-8`)
		c.Writer.WriteHeader(http.StatusOK)
		out := `{"code": 0, "msg":"success", "data":[]}`

		for _, row := range rows {
			out, _ = sjson.Set(out, "data.-1", row[0]) // 查询表明, 每行只有1列数据, 即表名
		}

		c.Writer.WriteString(out)
		c.Writer.Flush()
	})

	r.GET("/api/getColumns", func(c *gin.Context) {
		table := c.Query("table")
		rows := database.MysqlClient.ExecuteQuery(fmt.Sprintf(`show columns from %s`, table))
		c.Writer.Header().Add("Content-Type", `application/json; charset=utf-8`)
		c.Writer.WriteHeader(http.StatusOK)
		out := `{"code": 0, "msg":"success", "data":[]}`

		for _, row := range rows {
			out, _ = sjson.Set(out, "data.-1", row[0]) // 查询表明, 每行只有1列数据, 即表名
		}

		c.Writer.WriteString(out)
		c.Writer.Flush()
	})

	r.Run(":8080")
}
